//
//  LHLoginViewController.m
//  EPA
//
//  Created by 卢浩 on 16/4/25.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHLoginViewController.h"
#import "LHUserInfoManager.h"
#import "LHMenuViewController.h"
#import "LHDBManager.h"

@interface LHLoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *emailTF;

@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@end

@implementation LHLoginViewController

- (IBAction)loginAction:(UIButton *)sender {
    if (self.emailTF.text.length > 0 && self.passwordTF.text.length > 0) {
        NSURL *loginUrl = [NSURL URLWithString:@"http://api2.pianke.me/user/login"];
        NSMutableURLRequest *loginRequest = [NSMutableURLRequest requestWithURL:loginUrl];
        loginRequest.HTTPMethod = @"POST";
        loginRequest.HTTPBody = [[NSString stringWithFormat:@"email=%@&passwd=%@",self.emailTF.text,self.passwordTF.text] dataUsingEncoding:NSUTF8StringEncoding];
        NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:loginRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                //                NSLog(@"%@",dict);
                if (![[(NSDictionary *)dict[@"data"] allKeys] containsObject:@"msg"]) {
//                    NSLog(@"个人信息:%@",dict[@"data"]);
                    [self showAlertControllerWithStr:@"登陆成功" IsLogin:YES];
                    [[LHUserInfoManager shareManager] loginWithUserDict:dict[@"data"]];
                }else{
                    [self showAlertControllerWithStr:[NSString stringWithFormat:@"登陆失败,失败原因:%@",dict[@"data"][@"msg"]] IsLogin:NO];
                }
            }
        }];
        [dataTask resume];
    }

}

- (void)showAlertControllerWithStr:(NSString *)str IsLogin:(BOOL)isLogin{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登陆" message:str preferredStyle:(UIAlertControllerStyleAlert)];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            if (isLogin) {
                [self dismissViewControllerAnimated:YES completion:nil];
                
                //打开个人数据库
                [[LHDBManager shareManager] openDB];
            }
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    });
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
}

- (void)backAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
